package com.fofia.iotweb.jobs;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.log.StaticLog;
import com.fofia.iotweb.common.TimeHelper;
import com.fofia.iotweb.web.dbdomain.models.iot.IotTagXdataTime;
import com.fofia.iotweb.web.domain.service.FcDataService;
import com.fofia.iotweb.web.dbdomain.services.iot.IotTagXdataTimeService;
import org.noear.solon.annotation.Component;
import org.noear.solon.annotation.Inject;


@Component
public class RuminateXdataJob {

    @Inject
    private FcDataService _fcDataService;
    @Inject
    private IotTagXdataTimeService _tagXdataTimeService;

    //@Scheduled(cron = "0 5 0/1 * * ?")
    public void RunJob(){
        String tagIds = "202350000101,202350000103,202350000022,202350000023,202350000024,202350000030,202350000092";
        //tagId= StrUtil.format("标签id:t_{}",tagId);
        StaticLog.info(tagIds);
        String[] tagIdArray = tagIds.split(",");

        DateTime now=DateTime.now();
        DateTime lastHour= DateUtil.offsetHour(now, -1);
        String lastHourStr= StrUtil.format("{}-{}-{} {}:00:00",lastHour.year(),lastHour.month(),lastHour.dayOfMonth(),lastHour.hour(true));
        StaticLog.info("上一个小时：{}",lastHourStr);
        lastHour=DateUtil.parse(lastHourStr);
        DateTime lastHourEnd= DateUtil.offsetHour(lastHour, 1);
        StaticLog.info("上一个小时Start：{},上一个小时End：{}",lastHour,lastHourEnd);
        StaticLog.info("job:{} , from cron job.", DateTime.now());

        for (String tagId : tagIdArray){
            RunTag(tagId,lastHourStr,lastHourEnd);
        }

        //RunTag(tagIdArray[0]);
    }

    public void Run(){
        String tagIds = "202350000101,202350000103,202350000022,202350000023,202350000024,202350000030,202350000092";
        //tagId= StrUtil.format("标签id:t_{}",tagId);
        StaticLog.info(tagIds);
        String[] tagIdArray = tagIds.split(",");

        String ftime="2023-12-05 09:00:00";
        DateTime etime=new DateTime("2023-12-05 12:00:00", DatePattern.NORM_DATETIME_FORMAT);
        for (String tagId : tagIdArray){
            RunTag(tagId,ftime,etime);
        }

        //RunTag(tagIdArray[0]);
    }
    public void RunTag(String tagId,String ftime,DateTime etime){

        //String ftime="2023-12-04 00:00:00";
        //DateTime etime=new DateTime(etimeString, DatePattern.NORM_DATETIME_FORMAT);
        try{

            int limitVal=16;
            DateTime stime = new DateTime(ftime, DatePattern.NORM_DATETIME_FORMAT);
            int index=0;
            int xDataHour=0;
            while(true){
                if (index > 0)
                {
                    IotTagXdataTime model = new IotTagXdataTime();
                    model.setXdata(xDataHour);
                    model.setTagId(tagId);
                    var dayHour= DateUtil.offsetHour(stime, (index - 1));
                    String dayHourStr= DateUtil.format(dayHour, "yyyyMMddHH");
                    model.setDaytimeHour(Integer.parseInt(dayHourStr));
                    _tagXdataTimeService.insert(model);

                    xDataHour = 0;
                }

                int hourplus = 1 * index;
                DateTime startTime = DateUtil.offsetHour(stime, hourplus);

                if (startTime.isAfterOrEquals(etime))
                {
                    StaticLog.info("data process end at :{}",DateUtil.now());
                    break;
                }
                DateTime endTime= DateUtil.offsetHour(startTime, 1);
                StaticLog.info("start process tag:{},time range：{} to {}，please waiting....",tagId,startTime.toString(),endTime.toString());
                int page = 1;
                DateTime timeFlag = TimeHelper.minDateTime();
                while (true) {
                     var data=_fcDataService.getHistoryList(tagId,page,1000, DateUtil.formatDateTime(startTime), DateUtil.formatDateTime(endTime));
                    int count = data.size();
                     if(count==0){
                         break;
                     }
                     int xValueSecond = 0;
                     for (var model : data) {
                         var mtime = model.getUploadTime();
                         if (mtime.after(endTime))
                         {
                             break;
                         }

                         var records = RuminateHelper.parse(model.getSpeedHex());
                         int timeIndex = 0;
                         int timeStep = 80;
                         if (TimeHelper.sameTime(timeFlag, DateTime.of(mtime)))
                         {
                             timeIndex = 8;
                         }
                         else
                         {
                             if (xValueSecond > 0)
                             {
                                 xValueSecond =xValueSecond-80;
                                 if(xValueSecond>limitVal){
                                     xValueSecond=limitVal;
                                 }
                                 xDataHour +=xValueSecond;
                             }

                             xValueSecond = 0;
                         }
                         for (var record : records){
                             int absX = Math.abs(record.getX());
                             if (absX > 80 && absX > xValueSecond)
                             {
                                 xValueSecond = absX;
                             }
                         }
                         timeFlag = DateTime.of(mtime);

                         records= null;
                     }
                    data = null;
                    if (count < 1000)
                    {
                        break;
                    }
                    page++;
                }
                index++;
            }

        }catch (Exception e){
            StaticLog.error(e);
        }
    }
}
